<template>
  <div class="find-car-from page_pos_style" :style="{ top: `${phoneStatusBarHeight}`}">
    <navbar :title="title" ></navbar>
    <!-- <van-nav-bar
    :title="judgeStatus === 0 ? '添加爱车': '编辑爱车'"
    fixed
    placeholder
    :border='false'
    :right-text="judgeStatus === 0 ? '': '删除'"
    @click-right="deleteMyCar"
    >
      <template #left>
        <van-icon
          name="arrow-left"
          size="18"
          @click="goback"
        />
      </template>
    </van-nav-bar> -->
    <div class="page_pos_scroll" :style="{ top: `${phoneStatusBarHeight}`,marginTop:'12vw'}">

    <div class="car-add">
      <van-form :show-error="false">
        <div class="bgWhite">

        <van-field
          v-model="addCarFrom.vtdName"
          is-link
          readonly
          name="carType"
          label="车辆信息"
          placeholder="请选择车辆类型"
          @click="jmupToBrand"
          required
          :class="isCarType?'special':''"
          class="special-padding"
          size="large"
          :rules="[{ required:true, message: '请选择车辆类型' }]"
        />
       <van-field
        label="车牌号码"
        placeholder="请输入车牌号码"
        :required="true"
        type="text"
        v-model="addCarFrom.ciNo"
        name="phone"
        :class="isActive?'special':''"
        class="special-padding"
        size="large"
        maxlength="20"
        :rules="[{ validator , message: '请输入车牌号' }]"
        />

        <van-field
          label="识别代号"
          placeholder="(选填)"
          type="text"
          v-model="addCarFrom.vinNo"
          name="phone"
          class="special-padding"
          size="large"
          maxlength="20"
          ></van-field>

        <!--  -->
        <van-field
          label="发动机号"
          placeholder="(选填)"
          type="text"
          v-model="addCarFrom.engineNo"
          name="phone"
          class="special-padding"
          maxlength="20"
          size="large" />

		 </div>
       <!-- 车辆图片 -->
	   <div class="carPicture bgWhite">
	   <div class="tit-pic labelTit" >
	     <span >车辆图片</span>
	   </div>
	     <div class="form-upload-pic ">
			 <div class="flex-box">
				 <div class="lftLabel pad marRig">驾驶证照片</div>
         <van-uploader v-model="drivingImg" :after-read="getUrl" max-count="1"/>
			 </div>
			 <div class="flex-box">
				 <div class="lftLabel pad marRig">车辆图片</div>
         <van-uploader v-model="carImg" multiple max-count="10"/>
			 </div>
		 </div>
	   </div>
        <div class="but ">
          <van-button v-if="judgeStatus !== 0"  block type="info" @click="deleteMyCar" color="#FFDD00" :disabled="disabled">删除</van-button>
        </div>
        <div class="but ">
          <van-button  block type="info" @click="Submit" color="#FFDD00" :disabled="disabled">
            {{judgeStatus === 0 ? '添加': '保存'}}
          </van-button>
        </div>
      </van-form>
    </div>
    </div>
  </div>
</template>

<script>
import { areaList } from '../../../node_modules/@vant/area-data'
import { saveMyLovelyCar, getOneCar, editMyCar, deleteMyCar } from './api'
import upload from '../../common/upload'

export default{
  data() {
    return {
      title:"车辆信息",
      addCarFrom: {
        vtdName: '', // 车型名称
        vtdId: '', // 车型id
        biId: '', // 车系id
        biName: '', // 车系名称
        vnId: '', // 品牌id
        vnName: '', // 品牌名称
        vinNo: '',  // 识别代号
        ciNo:'', // 车牌号码
        engineNo:'', // 发动机号
        ulcFile: [{fileUrl: 'https://chezhuapp.oss-cn-beijing.aliyuncs.com/image/20211028/549abc28807e4194832efdeec431b05f.webp'}], // 车辆照片
        dlPhoto: '' // 驾驶证照片,只有一张
      },
      areaList,
      value: '',
      isActive: false,
      isCarType: false,
      drivingImg: [],
      carImg: [],
      judgeStatus: 0,
        // 获取屏幕状态栏高度
        phoneStatusBarHeight:'',
        loading: '',
        disabled: false
    }
  },
  methods: {
    goback() {
      this.$router.push({name: 'CarList'})
    },
    // 表单验证
    validator(val) {
      if(val === '') {
        this.isActive = true
        return false
      }
    },
    // 跳转到品牌选择页面
    jmupToBrand(){
      // 将部分信息存储到本地
      // 在这里需要做一个判断，判断本地和路由有没有村粗status
      localStorage.setItem('carBandPage','addCar')
      localStorage.setItem('editMyLovelyCar',JSON.stringify(this.addCarFrom))
      localStorage.setItem('LovelyCarStatus',this.$route.query.status)

      this.$router.push({
        name: 'SelectBrand',
        query:{
          myName:'addCar'
        }
      })
    },
    // 上传汽车图片
    uploadCarImg() {
      if(this.judgeStatus === 0 && this.carImg.length === 0) {
        this.addLoveCar()
      } else if (this.judgeStatus === 0 && this.carImg[0].file != undefined) {
        // this.addCarFrom.ulcFile = [{fileUrl: 'https://chezhuapp.oss-cn-beijing.aliyuncs.com/image/20211028/549abc28807e4194832efdeec431b05f.webp'}]
        const fileList = this.carImg.map(item => {
          let formData = new FormData()
          formData.append("file", item.file)
          return formData
        })
        // console.log(fileList)
        this.loading = this.$toast.loading({
          message: '图片较大\n请耐心等待...',
          forbidClick: true,
          duration: 0
        })
        upload(
          list => {
            let n = list.map(item => {
              return {fileUrl: item.url}
            })
            this.addCarFrom.ulcFile = n
            this.addLoveCar()
            this.loading.clear()
          },
          fileList
        )
      } else if (this.judgeStatus === 1) {
        let oldImg = []
        let newImg = []
        this.carImg.forEach(item => {
          if(item.url === undefined) {
            newImg.push(item)
          } else {
            oldImg.push(item)
          }
        })
        oldImg = oldImg.map(item => {
          return {fileUrl: item.url}
        })
        if(newImg.length > 0) {
          const fileList = newImg.map(item => {
            let formData = new FormData()
            formData.append("file", item.file)
            return formData
          })
          this.loading = this.$toast.loading({
            message: '图片较大\n请耐心等待...',
            forbidClick: true,
            duration: 0
          })
          upload(
            list => {
              let n = list.map(item => {
                return {fileUrl: item.url}
              })
              newImg = n
              this.addCarFrom.ulcFile = oldImg.concat(newImg)
              this.editMyLovelyCar()
              this.loading.clear()
            },
            fileList
          )
        } else if(oldImg.length > 0) {
          this.addCarFrom.ulcFile = oldImg
          this.editMyLovelyCar()
        } else if (oldImg.length <= 0) {
          this.addCarFrom.ulcFile = [{fileUrl: 'https://chezhuapp.oss-cn-beijing.aliyuncs.com/image/20211028/549abc28807e4194832efdeec431b05f.webp'}]
          this.editMyLovelyCar()
        }
      }

    },
    // 上传驾驶证照片
    getUrl(file) {
      // console.log(file,typeof(file))
      let formData = new FormData();
      formData.append("file", file.file);
      this.loading = this.$toast.loading({
          message: '图片较大\n请耐心等待...',
          forbidClick: true,
          duration: 0,
          overlay: true
        })
      upload(
        (list) => {
          list.forEach(item => {
            this.addCarFrom.dlPhoto = item.url
          })
          this.loading.clear()
        },
        [formData]
      )
    },

    // 添加爱车
    async addLoveCar() {
      this.disabled = false
      const {code} = await saveMyLovelyCar(this.addCarFrom)
      if(code === 0) {
        localStorage.removeItem('LovelyCarStatus');
        localStorage.removeItem('editMyLovelyCar');
        localStorage.removeItem('carBandPage');
        setTimeout(() => {
          this.$router.push({name: 'CarList'})
        }, 1000);
        
        this.$notify({
          type: 'success',
          message: '添加成功'
        })
        
        // 修改提示栏距离顶部高度
        this.$nextTick(()=>{
          document.querySelector('.van-popup--top').style.top = this.phoneStatusBarHeight
        })
      } else {
        this.$notify({
          type: 'danger',
          message: '添加失败'
        })
        this.disabled = true
      }
    },
    // 获取我的爱车信息
    async getMyCarData() {
      const {data} = await getOneCar(this.$route.query.id)
      console.log(data)
      this.addCarFrom = data
      // 图片回显
      if(data.dlPhoto != '') {
        this.drivingImg = [{url: data.dlPhoto, isImage: true}]
      }
      this.carImg = data.ulcFile.map(item => {
        return {url: item.fileUrl, isImage: true}
      })
      console.log(data)
    },
    // 编辑爱车
    async editMyLovelyCar() {
      this.disabled = true
      const {code} = await editMyCar(this.addCarFrom)
      if(code === 0) {
        localStorage.removeItem('LovelyCarStatus');
        localStorage.removeItem('editMyLovelyCar');
        localStorage.removeItem('carBandPage');
          this.$router.push({name: 'CarList'})
          this.$notify({
            type: 'success',
            message: '保存成功'
          })
      } else {
          this.$notify({
            type: 'danger',
            message: '保存失败'
          })
        this.disabled = false
      }
    },
    // 提交表单
    Submit() {
      let status = parseInt(localStorage.getItem("LovelyCarStatus"))
      // console.log(status)
      if(status === 0 || this.$route.query.status === 0) {
        if(this.addCarFrom.vtdName != "" && this.addCarFrom.ciNo != "") {
          this.uploadCarImg()
        } else {
          this.isActive = true
          this.isCarType = true
        }
      } else if(status === 1 || this.$route.query.status === 1) {
        if(this.addCarFrom.vtdName != "" && this.addCarFrom.ciNo != "") {
          // console.log(this.addCarFrom)
          this.uploadCarImg()
        } else {
          this.isActive = true
          this.isCarType = true
        }
      }
    },
    // 删除我的爱车
    async deleteMyCar() {
      let deleteItem = [this.$route.query.id]
      const {code} = await deleteMyCar(deleteItem)
      if(code === 0) {
        this.$router.push({name: 'CarList'})
        this.$notify({
          type: 'success',
          message: '删除成功'
        })
      } else {
        this.$notify({
          type: 'danger',
          message: '删除失败'
        })
      }
    }
  },
  created() {
      // 获取屏幕状态栏高度
      this.phoneStatusBarHeight = window.phoneStatusBarHeight
    if(this.$route.query.carType) {
      this.addCarFrom = JSON.parse(localStorage.getItem("editMyLovelyCar"))
      this.addCarFrom.vtdName = this.$route.query.carType
      this.addCarFrom.vnName = this.$route.query.brand
      this.addCarFrom.vnId = this.$route.query.vnid
      this.addCarFrom.vtdId = this.$route.query.vtdId
      this.addCarFrom.biId = this.$route.query.biId
      this.addCarFrom.biName = this.$route.query.biName
    }
    if(this.$route.query.status === 1 || parseInt(localStorage.getItem("LovelyCarStatus")) === 1) {
      // console.log(1)
      this.getMyCarData()
      this.judgeStatus = 1
    } else if (this.$route.query.status === 0 || parseInt(localStorage.getItem("LovelyCarStatus")) === 0) {
      this.judgeStatus = 0
    }
    document.title = this.judgeStatus == 0 ? '添加爱车': '编辑爱车'

  },
  mounted() {
    document.querySelector('body').setAttribute('style', 'background-color:#F8F8F8')
    // console.log(this.$route.query)
  }
}
</script>

<style lang="less">
  .van-cell--large .van-cell__title{
    color: #666666;
    font-family: PingFangSC-Regular, PingFang SC ;
    font-weight: 400;
    font-size: 16px;
  }
  .van-field__control{
    font-size: 16px;
  }
  .van-picker__confirm {
    color: #F6C401 !important;
  }
  .van-picker__cancel, .van-picker__confirm{
    font-size: 16px !important;
  }
</style>
<style scoped lang="less" scoped>
	/deep/ .lftLabel{
		width:7.8rem
	}
	.form-upload-pic >div {
		padding:.8rem;
	}
	/deep/ .car-add .bgWhite{
			background: white;
	}
	/deep/ .labelTit {
		background-color: #F8F8F8;

		    color: #b5b5b5;
		 	padding:1rem .5rem .5rem 1rem;
		}
	/deep/ .preview-cover {
    position: absolute;
    bottom: 0;
    box-sizing: border-box;
    width: 100%;
    padding: 4px;
    color: #fff;
    font-size: 12px;
    text-align: center;
    background: rgba(0, 0, 0, 0.3);
  }
  .find-car-from{
    background-color: #F8F8F8;
    width: 100%;
    // display: fixed;
  }
  .special-padding{
    padding: .8rem .8rem !important;
  }
  .remark{
    border: none;
    font-size: 16px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #B3B3B3;
    padding: 0 16px;
    height: 100px;
    width: 100%;
  }
  .special-font{
    padding: 16px 16px 0 16px;
    background-color: white;
    // height: 22px;
    font-size: 16px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #666666;
  }
  .special{
    border: 1px solid red;
  }
  .car-add{
    .van-cell--required::before{
      left: 23vw !important;
      font-size: 16px;
    }
    .but{
      margin: 20px 12px;
      .van-button{
        color: black !important;
        font-size: 17px;
        font-family: PingFang SC;
        font-weight: 500;
        color: #333333;
      }
    }
  }
</style>
